<?php
 function list_tukar($periode_id=0){
	my_set_code_js('
	
		function postDataPeriode(periode_id){ 
			location.href=\'index.php?com='.$_GET['com'].'&task=list_tukar&periode_id=\'+periode_id ;
		}

		function confirmDelete(id){
			var t = confirm(\'Yakin akan menghapus data ?\');
			if(t){
				location.href=\'index.php?com='.$_GET['com'].'&task=delete&id=\'+id;
			}
			return false;
		}
	');
	$header = array(
		'#'=>array('style'=>'text-align:center;border-bottom:2px solid;width:5%'),  
		'Tanggal'=>array('style'=>'border-bottom:2px solid;width:9%'), 
		'Nomor'=>array('style'=>'border-bottom:2px solid;width:12%'),   
		'NIK'=>array('style'=>'border-bottom:2px solid;width:9%'),  
		'Nama Karyawan'=>array('style'=>'border-bottom:2px solid;width:25%'),  
		'NIK '=>array('style'=>'border-bottom:2px solid;width:10%'),  
		'Nama Karyawan '=>array('style'=>'border-bottom:2px solid;width:25%'),  
		' '=>array('style'=>'border-bottom:2px solid;width:5%'), 
	);
	if($periode_id==0){
		$periode_id=get_periode_gaji() ;
	}		
	$periode = my_get_data_by_id('pr_periode','periode_id',$periode_id);
	if(isset($_GET['key']))
		$query = "SELECT * FROM a_tukar_shift a 
		INNER JOIN karyawan c ON a.karyawan_id = c.karyawan_id 
		INNER JOIN biodata d ON d.biodata_id = c.biodata_id
		WHERE c.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable) 
		AND (a.tanggal BETWEEN '{$periode['dari']}' AND '{$periode['sampai']}' )
		AND ( c.nik='{$_GET['key']}' OR d.nama LIKE '%{$_GET['key']}%' OR a.nomor_surat='{$_GET['key']}'
		OR a.tukar_karyawan_id IN 
		( 
		SELECT karyawan_id FROM karyawan h
		INNER JOIN biodata i ON h.biodata_id = h.biodata_id
		WHERE h.nik='{$_GET['key']}' ) 
		)
		ORDER BY tukar_shift_id  DESC";
	else
		$query = "SELECT * FROM a_tukar_shift  
		WHERE (tanggal BETWEEN '{$periode['dari']}' AND '{$periode['sampai']}' )
		ORDER BY tukar_shift_id  DESC
		 ";
 
	$result = my_query($query );
	$total_records = my_num_rows($result );
	$scroll_page =5;  
	$per_page =25;  
	$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1 ; 
	if($current_page < 1){
		$current_page = 1;
	}		 
	$pager_url  ="index.php?com={$_GET['com']}&task={$_GET['task']}&field={$_GET['field']}&key={$_GET['key']}&page=";	 
	$inactive_page_tag = 'style="padding:4px;background-color:#BBBBBB"';  
	$previous_page_text = ' Mundur '; 
	$next_page_text = ' Maju ';  
	$first_page_text = ' Awal '; 
	$last_page_text = ' Akhir ';
	
	$kgPagerOBJ = new kgPager();
	$kgPagerOBJ->pager_set(
		$pager_url, 
		$total_records, 
		$scroll_page, 
		$per_page, 
		$current_page, 
		$inactive_page_tag, 
		$previous_page_text, 
		$next_page_text, 
		$first_page_text, 
		$last_page_text ,$pager_url_last); 
	 		
	$result = my_query($query ." LIMIT ".$kgPagerOBJ->start.", ".$kgPagerOBJ->per_page); 	
	$row = array(); 
	$i = ($current_page  - 1 ) * 25; 
	while($ey = my_fetch_array($result)){
		$i++;
		$editproperty = array(
			'href'=>'index.php?com=a_tukar_shift&task=edit&id='.$ey['tukar_shift_id'],
			'title'=>'Edit'
		);
		$edit_button = button_icon( 'b_edit.png' , $editproperty  );

		$deleteproperty = array(
			'href'=>'javascript:; ',
			'onclick'=>'javascript:confirmDelete('.$ey['tukar_shift_id'].');',
			'title'=>'Delete'
		);
		$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );
		$karyawan = loaddata_karyawan($ey['karyawan_id']);
		$karyawan2 = loaddata_karyawan($ey['tukar_karyawan_id']);
		$row[] = array(
			'#'=>position_text_align ($i, 'center'), 
			'tgl'=>  date( 'd-m-Y' , strtotime($ey['tanggal']) ) ,  
			'nno'=>  $ey['nomor_surat'] ,
			'nik'=>  $karyawan['nik'] ,
			'nama'=>  $karyawan['nama_gelar'] ,
			'nik2'=>  $karyawan2['nik'] ,
			'nama2'=>  $karyawan2['nama_gelar'] ,
			'ops'=> position_text_align(  $edit_button.' '.$delete_button , 'right'),  
		);
		 
	}
	
	$datas = table_rows($row); 
	$menuontop = array(  
		'Tambah data'=>array('onclick'=>'javascript:location.href=\'index.php?com=a_tukar_shift&task=edit\''),
	);
	
	$query_check_periode = " SELECT * FROM pr_periode ORDER BY periode_id DESC";
	$result = my_query($query_check_periode);
	$prs = "";
	while($prow = my_fetch_array($result)){
		if($prow['periode_id'] ==$periode_id){
			$prs .='<option selected value="'.$prow['periode_id'].'">'.date('m-Y',strtotime($prow['tanggal'])).'</option>';
		}else{
			$prs .='<option value="'.$prow['periode_id'].'">'.date('m-Y',strtotime($prow['tanggal'])).'</option>';
		}	
	}
	$search = '<form method="GET"><input type="hidden" name="com" value="'.$_GET['com'].'"/>
	<table width="100%">
	<tr>
		<td>Pencarian</td>
		<td><input type="text" name="key" style="width:200px;"  value="'.(isset($_GET['key']) ? $_GET['key']: "").'" /> </td>
		<td><input type="submit" value=" CARI "/> </td> 
		<td>Periode</td>	 
		<td><select name="periode_id" id="periode_id" onchange="javascript:postDataPeriode(this.value)">'.$prs.'</select></td>				
	</tr>
	</table>
	</form>';

	$printmenu = additional_menu_on_list( $menuontop , $search);
	$paging = $kgPagerOBJ ->showPaging();
	return $printmenu .table_builder($header , $datas ,  7 , false ,$paging );
} 
 
function form_tukar_create( $id ){
	my_set_file_js(
		array(
			'components/system/jquery/combomulti/jquery.chainedSelects.js',
			'components/system/js/calendar/calendarDateInput.js' 
		)
	);
	
	my_set_file_js(
		array(
			'components/system/jquery/autocomplete/jquery.autocomplete.js'  
		)
	);
	my_set_file_css(
		array(
				'components/system/jquery/autocomplete/jquery.autocomplete.css' 
			)
	);

	my_set_code_js('  
		function findValue(li) {
			if( li == null ) return alert("No match!"); 
			if( !!li.extra ) var sValue = li.extra[0]; 
			else var sValue = li.selectValue;
		}

		function selectItem(li) {
			findValue(li);
		}

		function formatItem(row) {
			return   row[0] ;
		}

		function lookupAjax(){
			var oSuggest = $("#nama_karyawan")[0].autocompleter;
			oSuggest.findValue(); 
			return false;
		}
		$(document).ready(function() {
			$("#nama_karyawan").autocomplete(
				"autocomplete_daftar_karyawan.php",
				{
					delay:10,
					minChars:2,
					matchSubset:1,
					matchContains:1,
					cacheLength:5,
					onItemSelect:selectItem,
					onFindValue:findValue,
					formatItem:formatItem,
					autoFill:true
				}
			);
			 
		});

		function checkName(name){
			$.get("check_karyawan_names.php", { nama: name  },
			   function(data){
				 if(data ==  \'0\' ){
					alert(\'Nama karyawan \'+ name+\' tidak ditemukan\nHarap diperiksa kembali\');
					$(\'#nama_karyawan\').val(\'\');
					return false;
				 } 
			   });
		}
	');	

	my_set_code_js('  
		function findValue(li) {
			if( li == null ) return alert("No match!"); 
			if( !!li.extra ) var sValue = li.extra[0]; 
			else var sValue = li.selectValue;
		}

		function selectItem(li) {
			findValue(li);
		}

		function formatItem(row) {
			return   row[0] ;
		}

		function lookupAjax(){
			var oSuggest = $("#nama_karyawan_tukar")[0].autocompleter;
			oSuggest.findValue(); 
			return false;
		}
		$(document).ready(function() {
			$("#nama_karyawan_tukar").autocomplete(
				"autocomplete_daftar_karyawan.php",
				{
					delay:10,
					minChars:2,
					matchSubset:1,
					matchContains:1,
					cacheLength:5,
					onItemSelect:selectItem,
					onFindValue:findValue,
					formatItem:formatItem,
					autoFill:true
				}
			);
			 
		});

		function checkNameTukar(name){
			$.get("check_karyawan_names.php", { nama: name  },
			   function(data){
				 if(data ==  \'0\' ){
					alert(\'Nama karyawan \'+ name+\' tidak ditemukan\nHarap diperiksa kembali\');
					$(\'#nama_karyawan_tukar\').val(\'\');
					return false;
				 } 
			   });
		}
	');	
	
	
	$view = form_header( "seleski" , "seleski"  );
 	$fields = my_get_data_by_id('a_tukar_shift','tukar_shift_id',$id);
	$ftanggal = $ftanggalm = $ftanggals = date('d-m-Y');
	if($fields){
		list($yyyytanggal , $mmtanggal,$ddtanggal ) = explode("-" ,$fields['tanggal'] );
		list($yyyytanggals , $mmtanggals,$ddtanggals ) = explode("-" ,$fields['tanggal_permohonan'] );
		$ftanggal = $ddtanggal.'-'.$mmtanggal.'-'.$yyyytanggal;
		$ftanggals = $ddtanggals.'-'.$mmtanggals.'-'.$yyyytanggals;
	}
	
	$tanggal = array(
		'name'=>'tanggal',
		'value'=>(isset($_POST['tanggal'])? $_POST['tanggal'] : $ftanggal),
		'id'=>'tanggal',
		'type'=>'textfield',
		'size'=>'45'
	);
	$form_tanggal = form_calendar($tanggal);
	$view .= form_field_display( getNumber(date('Y'),date('m')) , "Nomor surat" );
	$view .= form_field_display( $form_tanggal  , "Pada Tanggal" );
	
	$karyawan_data = loaddata_karyawan(( $fields ? $fields['karyawan_id'] : 0));
	$karyawan = array(
		'name'=>'nama_karyawan',
		'value'=>(isset($_POST['nama_karyawan'])? $_POST['nama_karyawan'] : ( $fields ?  $karyawan_data['nik'].'/'.$karyawan_data['nama'] :'')  ),
		'id'=>'nama_karyawan',
		'type'=>'textfield',
		'size'=>'35',
		'onchange'=>'javascript:checkName(this.value)'
	);		
	$form_karyawan = form_dynamic($karyawan);
	$view .= form_field_display( $form_karyawan  , "NIK/Nama Karyawan"  );
	

/*	
	$kelompok_shifts = array();
	$query_kelompok_shift = "SELECT a.kelompok_shift_id,b.label,a.kelompok_shift_kode FROM a_kelompok_shift a 
		INNER JOIN a_waktu_kerja b ON a.waktu_kerja_id=b.waktu_kerja_id 
		ORDER BY a.kelompok_shift_id ";
	$re = my_query($query_kelompok_shift);
	while($row = my_fetch_array($re) ){
		$kelompok_shifts[$row['kelompok_shift_id']] =$row['label'].'/'.$row['kelompok_shift_kode'];
	}
	
	$shift_dari = array(
		'name'=>'shift_dari',
		'id'=>'shift_dari',
		'value'=>isset($_POST['shift_dari']) ? $_POST['shift_dari'] : $fields['shift_dari'] 
		);
	$form_field_shift_dari = form_dropdown($shift_dari , $kelompok_shifts);
	$view .= form_field_display( $form_field_shift_dari   , "Dari Shift");

	$shift_ke = array(
		'name'=>'shift_ke',
		'id'=>'shift_ke',
		'value'=>isset($_POST['shift_ke']) ? $_POST['shift_ke'] : $fields['shift_ke'] 
		);
	$form_field_shift_ke = form_dropdown($shift_ke , $kelompok_shifts);
	$view .= form_field_display( $form_field_shift_ke   , "Ke Shift");
*/
	$karyawan_data = loaddata_karyawan(( $fields ? $fields['tukar_karyawan_id'] : 0));
	$tukar_karyawan_id = array(
		'name'=>'nama_karyawan_tukar',
		'value'=>(isset($_POST['nama_karyawan_tukar'])? $_POST['nama_karyawan_tukar'] :  ( $fields ?  $karyawan_data['nik'].'/'.$karyawan_data['nama'] :'') ),
		'id'=>'nama_karyawan_tukar',
		'type'=>'textfield',
		'size'=>'35',
		'onchange'=>'javascript:checkNameTukar(this.value)'
	);
	$form_tukar_karyawan_id = form_dynamic($tukar_karyawan_id);
	$view .= form_field_display( $form_tukar_karyawan_id  , "Tukar dinas dengan <br>(NIK/Nama Karyawan)"  );

	$keperluan = array(
		'name'=>'keperluan',
		'value'=>( isset($_POST['keperluan']) ? $_POST['keperluan'] : $fields['keperluan'] ),
		'id'=>'keperluan', 
		'cols'=>'45',
		'rows'=>'4'
	);
	$form_field_keperluan = form_textarea($keperluan );
	$view .= form_field_display( $form_field_keperluan , "Keperluan"   );
	
	$tanggal_permohonan = array(
		'name'=>'tanggal_permohonan',
		'value'=>(isset($_POST['tanggal_permohonan'])? $_POST['tanggal_permohonan'] : $ftanggals),
		'id'=>'tanggal_permohonan',
		'type'=>'textfield',
		'size'=>'45'
	);
	$form_tanggal = form_calendar($tanggal_permohonan);
	$view .= form_field_display( $form_tanggal  , "Tanggal Permohonan" );
	

	$submit = array(
		'value' => ( $id ==0 ? ' Simpan ' :'  Update  '),
		'name' => 'simpan', 
		'type'=>'submit','class'=>'main_button'
	);
	$form_submit= form_dynamic($submit); 

	$back = array(
		'value' => ' Batal  ' ,
		'name' => 'back', 'onclick'=>'location.href=\'index.php?com=a_tukar_shift\'',
		'type'=>'button','class'=>'main_button'
	);
	$form_back= form_dynamic($back); 
	$view .= form_field_display( $form_submit .' '. $form_back  , "&nbsp;" ,  "" );	
	$view .= form_footer( );
	return $view;
}

function form_tukar_submit($id = 0){
	$karyawan_id = check_karyawan_by_nik_nama($_POST['nama_karyawan']);
	$tukar_karyawan_id = check_karyawan_by_nik_nama($_POST['nama_karyawan_tukar']);

	if($_POST){
		list( $ddtanggal, $mmtanggal,$yyyytanggal ) = explode("-" ,$_POST['tanggal'] );
		list($yyyytanggals , $mmtanggals,$ddtanggals ) = explode("-" ,$_POST['tanggal_permohonan'] );
		$ftanggal = $yyyytanggal.'-'.$mmtanggal.'-'.$ddtanggal;
		$ftanggals = $ddtanggals.'-'.$mmtanggals.'-'.$yyyytanggals;		 
	}
	
	$k1 = get_original_shift($karyawan_id , $ddtanggal);
	$k2 = get_original_shift($tukar_karyawan_id , $ddtanggal);


	$query1 = "UPDATE a_temp_jadwal_karyawan SET h{$ddtanggal} = '{$k2}' WHERE karyawan_id = {$karyawan_id} ";
	my_query($query1);
	$query2 = "UPDATE a_temp_jadwal_karyawan SET h{$ddtanggal} = '{$k1}' WHERE karyawan_id = {$tukar_karyawan_id} ";
	my_query($query2);
	

	$datas = array(
		'karyawan_id'=> my_type_data_int($karyawan_id),
		'nomor_surat'=>my_type_data_str(getNumber(date('Y'),date('m'))), 
		'tukar_karyawan_id'=> my_type_data_int($tukar_karyawan_id),
		'tanggal'=>my_type_data_str($ftanggal), 
		'shift_dari'=>my_type_data_int($k1 ),
		'shift_ke'=>my_type_data_int($k2 ),
		'tanggal_permohonan'=>my_type_data_str($ftanggals), 
		'keperluan'=>my_type_data_str($_POST['keperluan']),
	);
	
	
	if($id > 0){
		my_query("DELETE FROM a_tukar_shift_detail WHERE tukar_shift_id = {$id} ");
		$datas = array(
			'karyawan_id'=> my_type_data_int($karyawan_id),
			'tukar_karyawan_id'=> my_type_data_int($tukar_karyawan_id),
			'tanggal'=>my_type_data_str($ftanggal), 
			'shift_dari'=>my_type_data_int($k1 ),
			'shift_ke'=>my_type_data_int($k2 ),
			'tanggal_permohonan'=>my_type_data_str($ftanggals), 
			'keperluan'=>my_type_data_str($_POST['keperluan']),
		);
		$datask1 = array(
			'tukar_shift_id' => my_type_data_int($id),
			'karyawan_id' => my_type_data_int($karyawan_id),
			'pindah_jadwal_kerja_kelompok_id' => my_type_data_int($k2),
		);
		my_insert_record('a_tukar_shift_detail' , $datask1);
		$datask2 = array(
			'tukar_shift_id' => my_type_data_int($id),
			'karyawan_id' => my_type_data_int( $tukar_karyawan_id ),
			'pindah_jadwal_kerja_kelompok_id' => my_type_data_int($k1),
		);
		my_insert_record('a_tukar_shift_detail' , $datask2);
		return my_update_record('a_tukar_shift','tukar_shift_id',$id,$datas);
	}
	
	
	$new_id = my_insert_record('a_tukar_shift',$datas);
	$datask1 = array(
		'tukar_shift_id' => my_type_data_int($new_id),
		'karyawan_id' => my_type_data_int($karyawan_id),
		'pindah_jadwal_kerja_kelompok_id' => my_type_data_int($k2 ),
	);
	my_insert_record('a_tukar_shift_detail' , $datask1);
	$datask2 = array(
		'tukar_shift_id' => my_type_data_int($new_id),
		'karyawan_id' => my_type_data_int( $tukar_karyawan_id ),
		'pindah_jadwal_kerja_kelompok_id' => my_type_data_int($k1 ),
	);
	my_insert_record('a_tukar_shift_detail' , $datask2);
	return $new_id;
}

function form_tukar_validate($id){
	$errsubmit = false;
	$err = array();

	if( $errsubmit){
		return $err;
	}
	return $errsubmit;
}

function delete_tukar($id){
	$query = "DELETE FROM a_tukar_shift WHERE tukar_shift_id ={$id} ";
	return my_query($query);
}	

function getNumber($tahun,$bulan){
	$query = "SELECT max(nomor_surat) as nn FROM a_tukar_shift 
		WHERE nomor_surat LIKE '%{$tahun}{$bulan}%' ";
	$res = my_query($query);
	$row = my_fetch_array($res); 
 
	return $tahun.$bulan.sprintf('%05d',(int)substr($row['nn'] ,6,12) + 1);
}

function get_original_shift($karyawan_id , $tgl){
	$query = "SELECT h{$tgl} FROM a_temp_jadwal_karyawan WHERE karyawan_id = {$karyawan_id} LIMIT 1";
	$result = my_query($query);
	$row = my_fetch_array($result);
	return $row['h'.$tgl];
}

/*
	================== TIDAK DIPAKAI ==================================
*/
function tukar_shift_batch(){
	if(!function_exists('get_karyawan_schedule')){	return false;} 
	$query = "SELECT * FROM a_tukar_shift";
	$result = my_query($query);
	while($row = my_fetch_array($result)){
		$tahun = date('Y',strtotime($row['tanggal']));
		$bulan = date('m',strtotime($row['tanggal']));
		$dup = array(
			'nomor_surat'=>getNumber($tahun,$bulan),
		);
		my_update_record('a_tukar_shift','tukar_shift_id',$row['tukar_shift_id'],$dup);
		
		$k1 = get_karyawan_schedule($row['karyawan_id'] 	,	$row['tanggal']);
		$k2 = get_karyawan_schedule($row['tukar_karyawan_id'] ,$row['tanggal']);
		$datask1 = array(
			'tukar_shift_id' => my_type_data_int($row['tukar_shift_id']),
			'karyawan_id' => my_type_data_int($row['karyawan_id'] ),
			'pindah_jadwal_kerja_kelompok_id' =>my_type_data_int($k2 ),
		);
		my_insert_record('a_tukar_shift_detail' , $datask1);
		$datask2 = array(
			'tukar_shift_id' => my_type_data_int($row['tukar_shift_id']),
			'karyawan_id' => my_type_data_int( $row['tukar_karyawan_id'] ),
			'pindah_jadwal_kerja_kelompok_id' => my_type_data_int($k1 ),
		);
		my_insert_record('a_tukar_shift_detail' , $datask2);
	}
}

function update_tukar_shift(){
	
	$query = "SELECT * FROM a_tukar_shift WHERE DATE(tanggal) > '2013-09-10' ";
	$result = my_query($query);
	$i=0;
	while($row = my_fetch_array($result)){
		$i++;
my_query("DELETE FROM a_tukar_shift_detail WHERE tukar_shift_id = {$row['tukar_shift_id']} ");
		list($yy,$mm,$ddtanggal) = explode("-" , $row['tanggal']);
		$k1 = get_original_shift($row['karyawan_id'] , $ddtanggal);
		$k2 = get_original_shift($row['tukar_karyawan_id'] , $ddtanggal);
		$datas = array( 
			'shift_dari'=>my_type_data_int($k1 ),
			'shift_ke'=>my_type_data_int($k2 ), 
		);
		$datask1 = array(
			'tukar_shift_id' => my_type_data_int($id),
			'karyawan_id' => my_type_data_int($karyawan_id),
			'pindah_jadwal_kerja_kelompok_id' => my_type_data_int($k2),
		);
		my_insert_record('a_tukar_shift_detail' , $datask1);
		$datask2 = array(
			'tukar_shift_id' => my_type_data_int($id),
			'karyawan_id' => my_type_data_int( $tukar_karyawan_id ),
			'pindah_jadwal_kerja_kelompok_id' => my_type_data_int($k1),
		);
		my_insert_record('a_tukar_shift_detail' , $datask2);
		my_update_record('a_tukar_shift','tukar_shift_id',$row['tukar_shift_id'],$datas);
	}
	return $i;
}
